package com.itheima.tanhua.autoconfig.template;

import com.itheima.tanhua.autoconfig.properties.SmsProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 发送短信的工具类
 */
public class SMSTemplate {

    private RestTemplate restTemplate;

    private SmsProperties smsProperties;

    private SMSTemplate() {
    }

    public SMSTemplate(RestTemplate restTemplate, SmsProperties smsProperties) {
        this.restTemplate = restTemplate;
        this.smsProperties = smsProperties;
    }

    private static String Url = "http://106.ihuyi.com/webservice/sms.php?method=Submit";

    public boolean sendMessage(String mobile, String validateCode) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        //提交参数设置
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("account", smsProperties.getAccount());
        map.add("password", smsProperties.getPassword());
        map.add("mobile", mobile);
        map.add("content", "您的验证码是：" + validateCode + "。请不要把验证码泄露给其他人。");
        map.add("format", "json");

        // 组装请求体
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

        // 发送post请求，并打印结果，以String类型接收响应结果JSON字符串
        Map<String, Object> result = null;
        try {
            result = restTemplate.postForObject(Url, request, Map.class);
            if (result.getOrDefault("code", "0").toString().equals("2")) {
                return true;
            } else {
                throw new Exception("验证码发送异常：" + result.getOrDefault("msg", "").toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

    }

    public void testSms(String mobile, String validateCode) {
        System.out.println(":::::::::::::::::::短信下发成功:::::::::::::::::::");
        System.out.println(":::::::::::::::::::用户手机号::::::::【" + mobile + "】");
        System.out.println(":::::::::::::::::::验证码:::::::::::【" + validateCode + "】");
    }

}